import requests
import numpy as np
import time
from datetime import datetime

# ------------------- 接口配置 -------------------
URL = "http://127.0.0.1:8000/ecg_upload"
DEVICE_ID = "ECG2025000000"        # 必须与数据库 Device.device_id 一致
POINTS_PER_SECOND = 250   # 采样率 250Hz
UPLOAD_INTERVAL = 1       # 每次上传1秒的数据
DURATION_SEC = 30         # 模拟30秒数据，方便测试

# ------------------- 模拟心电波形 -------------------
def ecg_waveform(t):
    from math import exp
    p = 0.15 * exp(-((t - 0.1) ** 2) / (2 * 0.015 ** 2))
    q = -0.25 * exp(-((t - 0.18) ** 2) / (2 * 0.010 ** 2))
    r = 1.2 * exp(-((t - 0.20) ** 2) / (2 * 0.012 ** 2))
    s = -0.35 * exp(-((t - 0.25) ** 2) / (2 * 0.015 ** 2))
    t_wave = 0.3 * exp(-((t - 0.35) ** 2) / (2 * 0.04 ** 2))
    return p + q + r + s + t_wave

# ------------------- 生成数据 -------------------
hr = 75
period = 60.0 / hr
samples_per_beat = int(period * POINTS_PER_SECOND)
beats = int(DURATION_SEC / period)


data = []
timestamps = []  # 用于存储每个数据点的时间戳
start_time = time.time()  # 当前时间戳，作为开始时间

for _ in range(beats):
    for i in range(samples_per_beat):
        val = ecg_waveform(i / POINTS_PER_SECOND) + np.random.uniform(-0.02, 0.02)
        data.append(round(val, 3))
        timestamps.append(round(start_time + i / POINTS_PER_SECOND, 3))  # 生成时间戳
    start_time += period  # 每次心跳周期结束后更新时间戳


# ------------------- 模拟上传（修正版）-------------------
for sec in range(0, DURATION_SEC, UPLOAD_INTERVAL):
    start = sec * POINTS_PER_SECOND
    end = (sec + UPLOAD_INTERVAL) * POINTS_PER_SECOND
    batch = data[start:end]
    batch_timestamps = timestamps[start:end]
    data_str = ",".join(map(str, batch))
    timestamps_str = ",".join(map(str, batch_timestamps))

    res = requests.post(URL, data={
        "device_id": DEVICE_ID,
        "data": data_str,
        "timestamps": timestamps_str   # 只上传完整的时间戳序列
    })
    # 可选：打印状态以便调试
    # print(sec, res.status_code, res.text)

    time.sleep(1)  # 每秒上传一次更真实

